package com.atguigu.srb.sms.controller;


import com.atguigu.common.exception.Assert;
import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.util.RandomUtils;
import com.atguigu.common.util.RegexValidateUtils;
import com.atguigu.srb.sms.client.CoreUserInfoClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
@Slf4j
public class ApiSmsController {

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    CoreUserInfoClient coreUserInfoClient;

    /**
     * 获取手机号对应的验证码，并将将验证码存入到redis中
     * 1.校验手机号是否为空，手机号格式是否正确
     * 2.调用RandomUtils工具类得到验证码
     * 3.调用短信发送服务将验证码发送至指定的手机号上
     * 4.将验证码保存至redis中
     */
    @ApiOperation("获取短信验证码")
    @GetMapping("/send/{mobile}")
    public R send(
            @ApiParam(value = "手机号", required = true)
            @PathVariable String mobile) {
        //MOBILE_NULL_ERROR(-202, "手机号不能为空"),
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_ERROR);
        //MOBILE_ERROR(-203, "手机号不正确"),
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);

        //手机号是否注册
        boolean checkMobile = coreUserInfoClient.checkMobile(mobile);
        if(checkMobile){
            log.info("该手机号用户存在");
        }else{
            log.error("手机号未注册");
        }
        Assert.isTrue(checkMobile == false, ResponseEnum.MOBILE_EXIST_ERROR);

        //生成验证码
        String code = RandomUtils.getSixBitRandom();
        log.info("{}mobile生成的验证码为{}", mobile, code);

        //调用短信发送服务将验证码发送至手机

        try {
            //将验证码保存至redis
            log.info("将验证码保存至redis");
            redisTemplate.opsForValue().set("srb:sms:code:" + mobile, code, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("redis服务异常");
            e.printStackTrace();
            throw new BusinessException(ResponseEnum.ERROR);
        }

        return R.ok().message("获取短信验证码成功");
    }
}
